from django.db.models import Q
from django.shortcuts import render,redirect,HttpResponse
from .models import *
from django.views import View
from django.urls import reverse
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
from django.contrib import auth
# Create your views here.

class Go(View):
    def get(self,request):
        return render(request,'go.html')
    def post(self,request):
        username=request.POST.get('username')
        password=request.POST.get('password')
        user=auth.authenticate(username=username,password=password)
        if username is not None:
            users=auth.login(request,user)
            rep=redirect(reverse('app0:index'))
            rep.set_cookie('username',username,3600)
            return rep
        else:
            return HttpResponse('登录失败')


class Index(View):
    def get(self,request,page=1):
        data=Books.objects.all().order_by('price')
        pagee = Paginator(data,2)
        pager = pagee.get_page(page)
        username=request.COOKIES.get('username')
        # try:
        #     con = paginss.page(page)
        # except PageNotAnInteger:
        #     con = paginss.page(1)
        # except EmptyPage:
        #     con = paginss.page(paginss.num_pages)
        return render(request,'index.html',locals())

class Delet(View):
    def get(self,request,id):
        Books.objects.get(id=id).delete()
        return redirect(reverse('app0:index'))

class Updat(View):
    def get(self,request,u_id):
        data=Books.objects.filter(id=u_id)
        return render(request,'update.html',{'data':data})
    def post(self,request,u_id):
        # id=request.POST.get('id')
        name=request.POST.get('name')
        price=request.POST.get('price')
        Books.objects.filter(id=u_id).update(name=name,price=price)
        return redirect(reverse('app0:index'))

class Add(View):
    def get(self,request):
        return render(request,'add.html')
    def post(self,request):
        name=request.POST.get('name')
        price=request.POST.get('price')
        Books.objects.create(name=name,price=price)
        return redirect(reverse('app0:index'))

def serch(request,page=1):
    name=request.GET.get('name')
    q=Q(name__contains=name)
    data = Books.objects.filter(q).order_by('price')
    pagee = Paginator(data,2)
    pager = pagee.get_page(page)
    return render(request,'base.html',locals())
class Price(View):
    def get(self,request,id):
        data = Books.objects.filter(id=id)
        print(data)
        return render(request, 'price.html', {'data': data})


def a(request):
    course = Course.object.all()
    pagin = Paginator(course, 2)
    g = request.GET.get('page', '1')
    try:
        g=int(g)
        if g<0:
            g=1
    except Exception as e:
        g=1
    pagex=pagin.get_page(g)
    pagex=pagex.object_list

    return render(request,'paging.html',{"pagexx":pagex})
